package main;

import java.util.Random;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.game.LayerManager;
import javax.microedition.lcdui.game.Sprite;
import javax.microedition.lcdui.game.TiledLayer;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
/**
 *
 * @author user
 */
public class LuckyCoinCanvas extends GameCanvas implements Runnable, IMessageListenner {

    //-------------Final Static Fields--------------------    
    public final static int ITEM_APPLE = 1;
    public final static int ITEM_ORANGE = 2;
    public final static int ITEM_MELLON = 3;
    public final static int ITEM_BELL = 4;
    public final static int ITEM_WATER_MELLON = 5;
    public final static int ITEM_STAR = 6;
    public final static int ITEM_SEVEN = 7;
    public final static int ITEM_BAR = 8;
    public final static int ITEM_MORE_TIME = 0;
    protected static final int DIALOG_HEIGHT = 40;
    public final static int[] bonusMultiItem = {5, 10, 15, 20, 20, 30, 40, 100};
    /*
     * ----state----
     */
    public final static int STATE_WAITING = 0;
    public final static int STATE_RUNNING = 1;
    public final static int STATE_SHOW_RESULT = 2;
    public final static int STATE_MENU = 3;
    /*
     * ------Screen type-----
     */
    public final static int SCREEN_H320 = 0;
    public final static int SCREEN_H240 = 1;
    //--------------Fields---------------------------------
    public Main midlet;
    public Thread gameThread;
    public boolean running;
    public int delay = 50;
    public int state, checkPointState;
    public int screenType;
    public int bonus;
    public int tempBonus;
    public long credit = 0;
    public long checkpointCredit;
    public int redBet, greenBet;
    public int typeLed, bufferTypeLed;
    public int multiBet = 1;
    public int indexMode;
    public int indexListItems;
    public int indexBigLed;
    public int indexItemRolling;
    public int iMenu;
    public int typeItemFinal = -1, indexItemFinal;
    public int buffertypeItemFinal;
    public boolean isItemFinalSmall, bufferIsItemFinalSmall;
    public boolean isTurnLeft = false, isTurnRight = true;
    public boolean isWaitMoreTime;
    public String[] menuStr = {"Cược x10.000", "Cược x1000", "Cược x100", "Reset", "Thoát"};
    //--------------Graphics Fields-----------------------
    public LuckyCoinDesign design;
    public LayerManager lm;
    public TiledLayer bottomBar;
    public ItemGame itemsCircle[];
    public ItemGame listItems[];
    public TiledLayer textBoxListItems[];
    public TiledLayer textBoxBonus;
    public TiledLayer textBoxCredit;
    public Sprite[] smallLeds;
    public Sprite[] bigLeds;
    public TiledLayer[] textBoxBigLeds;
    public TiledLayer selectMenu;
    public Sprite creditIcon;
    //-----------------Other Fields------------------------
    public String dialogString;
    public boolean isKillClient;
    public boolean isLostConnection;
    public int timeChangeSpeed, timeSmLedSplink;
    public int timeWaitMoreTime;
    public int countBigSplink;
    public int indexSmallLed;
    public int timeItemChange;
    public int bufferMoreTime;

    public LuckyCoinCanvas() {
        super(false);
    }

    public LuckyCoinCanvas(Main midlet) {
        super(false);
        setFullScreenMode(true);
        this.midlet = midlet;
        int screenMode = (this.getWidth() < this.getHeight() ? Scene.SCREEN_PORTRAIT : Scene.SCREEN_LANDSCAPE);
        design = new LuckyCoinDesign(this.getWidth(), this.getHeight(), screenMode);
        checkScreenType();
        init();
        // start();
    }

    public void disposeObject() {
        menuStr = null;
        //--------------Graphics Fields-----------------------
        design = null;
        lm = null;
        bottomBar = null;
        itemsCircle = null;
        listItems = null;
        textBoxListItems = null;
        textBoxBonus = null;
        textBoxCredit = null;
        smallLeds = null;
        bigLeds = null;
        textBoxBigLeds = null;
        selectMenu = null;
        creditIcon = null;
        gameThread = null;
        Debug.d("dispose object");
    }

    public void start() {
        running = true;
        gameThread = new Thread(this);
        gameThread.start();
    }

    private void init() {
        Request.setMessageListenner(this);
        Request.chosseGame(Constants.XENG);
        checkpointCredit = credit;
        try {
            lm = new LayerManager();
            bottomBar = design.creatBottomBar();
            /*
             * -----Init All Items---------
             */
            creatItemsCircle();
            int xAnchor = this.getWidth() / 2 - (7 * itemsCircle[0].getWidth()) / 2;
            int yAnchor = 0;
            if (screenType == SCREEN_H320) {
                yAnchor = this.getHeight() - bottomBar.getHeight() - 60 - 7 * itemsCircle[0].getHeight();
            } else if (screenType == SCREEN_H240) {
//                yAnchor = this.getHeight() - 60 - 7 * itemsCircle[0].getHeight();
                yAnchor = 0;
            }
            for (int i = 0; i < itemsCircle.length; i++) {
                if (i < 6) {
                    itemsCircle[i].setPosition(xAnchor + i * itemsCircle[i].getWidth(), yAnchor);
                } else if (i < 12) {
                    itemsCircle[i].setPosition(xAnchor + 6 * itemsCircle[0].getWidth(), yAnchor + (i - 6) * itemsCircle[i].getHeight());
                } else if (i < 18) {
                    itemsCircle[i].setPosition(xAnchor + (18 - i) * itemsCircle[0].getWidth(), yAnchor + 6 * itemsCircle[i].getHeight());
                } else {
                    itemsCircle[i].setPosition(xAnchor, yAnchor + (24 - i) * itemsCircle[0].getHeight());
                }
            }

            //-----------------------------------------
            smallLeds = new Sprite[8];
            for (int i = 0; i < smallLeds.length; i++) {
                smallLeds[i] = design.getSmallLed();
                if (i < 4) {
                    smallLeds[i].setFrameSequence(new int[]{0, 1});
                } else {
                    smallLeds[i].setFrameSequence(new int[]{2, 3});
                }
            }
            bigLeds = new Sprite[2];
            for (int i = 0; i < bigLeds.length; i++) {
                bigLeds[i] = design.getBigLed();
                if (i == 0) {
                    bigLeds[i].setFrameSequence(new int[]{2, 3});
                    bigLeds[i].setFrame(1);
                } else {
                    bigLeds[i].setFrameSequence(new int[]{0, 1});
                }
            }
            textBoxBigLeds = new TiledLayer[bigLeds.length];
            for (int i = 0; i < textBoxBigLeds.length; i++) {
                textBoxBigLeds[i] = design.getTextBox(36);
            }
            //--------------------------------------------------------
            listItems = new ItemGame[8];
            textBoxListItems = new TiledLayer[listItems.length];
            for (int i = 0; i < listItems.length; i++) {
                listItems[i] = new ItemGame(i + 1, true);
                textBoxListItems[i] = design.getTextBox(listItems[i].getWidth());
            }
            creditIcon = design.getCredit();
            /*
             * -------
             */
            if (screenType == SCREEN_H320) {
                textBoxBonus = design.getTextBox(72);
                textBoxCredit = design.getTextBox(72);
            } else if (screenType == SCREEN_H240) {
                textBoxBonus = design.getTextBox(54);
                textBoxCredit = design.getTextBox(54);
            }
            selectMenu = design.getSelectedMenu(110);
            //---------------Init Position-------------------
            int xListItemAnchor = this.getWidth() / 2 - 8 * (listItems[0].getWidth() + 1) / 2;
            int yListItemAnchor = yAnchor + 7 * itemsCircle[0].getHeight() + 2;
            for (int i = 0; i < listItems.length; i++) {
                textBoxListItems[i].setPosition(xListItemAnchor + (7 - i) * (listItems[i].getWidth() + 1),
                        yListItemAnchor);
                if (screenType == SCREEN_H320) {
                    listItems[i].setPosition(xListItemAnchor + (7 - i) * (listItems[i].getWidth() + 1),
                            yListItemAnchor + textBoxListItems[i].getHeight() + 1);
                    lm.append(textBoxListItems[i]);
                } else if (screenType == SCREEN_H240) {
                    listItems[i].setPosition(xListItemAnchor + (7 - i) * (listItems[i].getWidth() + 1),
                            this.getHeight() - listItems[i].getHeight());
                }
                listItems[i].bg.setFrameSequence(new int[]{1});
            }
            int xLedAnchor = this.getWidth() / 2 - 8 * smallLeds[0].getWidth() / 2;
            int yLedAnchor = yAnchor + 6 * itemsCircle[0].getHeight() - 4 - smallLeds[0].getHeight();
            for (int i = 0; i < smallLeds.length; i++) {
                smallLeds[i].setPosition(xLedAnchor + i * smallLeds[i].getWidth(), yLedAnchor);
                lm.append(smallLeds[i]);
            }
            if (screenType == SCREEN_H320) {
                textBoxBonus.setPosition(xAnchor, yAnchor - 3 - textBoxBonus.getHeight());
                textBoxCredit.setPosition(xAnchor + 7 * itemsCircle[0].getWidth() - textBoxCredit.getWidth(),
                        yAnchor - 3 - textBoxCredit.getHeight());
            } else {
                textBoxBonus.setPosition(3, 3);
                textBoxCredit.setPosition(this.getWidth() - textBoxCredit.getWidth() - 3, 3);
            }
            lm.append(textBoxBonus);
            lm.append(textBoxCredit);
            bigLeds[1].setPosition(xAnchor + itemsCircle[0].getWidth() + (5 * itemsCircle[0].getWidth() / 4 - bigLeds[0].getWidth() / 2),
                    yLedAnchor - 4 - bigLeds[0].getHeight());
            bigLeds[0].setPosition(xAnchor + itemsCircle[0].getWidth() + (3 * 5 * itemsCircle[0].getWidth() / 4 - bigLeds[0].getWidth() / 2),
                    yLedAnchor - 4 - bigLeds[0].getHeight());
            for (int i = 0; i < textBoxBigLeds.length; i++) {
                textBoxBigLeds[i].setPosition(bigLeds[i].getX() + bigLeds[i].getWidth() / 2 - textBoxBigLeds[i].getWidth() / 2,
                        bigLeds[i].getY() - 3 - textBoxBigLeds[i].getHeight());
                lm.append(textBoxBigLeds[i]);
                lm.append(bigLeds[i]);
            }
            bottomBar.setPosition(0, this.getHeight() - bottomBar.getHeight());
            if (screenType == SCREEN_H240) {
                bottomBar.setVisible(false);
            }
            lm.append(bottomBar);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void creatItemsCircle() {
        itemsCircle = new ItemGame[24];
        itemsCircle[0] = new ItemGame(ITEM_ORANGE, false);
        itemsCircle[1] = new ItemGame(ITEM_BELL, false);
        itemsCircle[2] = new ItemGame(ITEM_BAR, true);
        itemsCircle[3] = new ItemGame(ITEM_BAR, false);
        itemsCircle[4] = new ItemGame(ITEM_APPLE, false);
        itemsCircle[5] = new ItemGame(ITEM_APPLE, true);
        itemsCircle[6] = new ItemGame(ITEM_MELLON, false);
        itemsCircle[7] = new ItemGame(ITEM_WATER_MELLON, false);
        itemsCircle[8] = new ItemGame(ITEM_WATER_MELLON, true);
        itemsCircle[9] = new ItemGame(ITEM_MORE_TIME, false);
        itemsCircle[10] = new ItemGame(ITEM_APPLE, false);
        itemsCircle[11] = new ItemGame(ITEM_ORANGE, true);
        itemsCircle[12] = new ItemGame(ITEM_ORANGE, false);
        itemsCircle[13] = new ItemGame(ITEM_BELL, false);
        itemsCircle[14] = new ItemGame(ITEM_SEVEN, true);
        itemsCircle[15] = new ItemGame(ITEM_SEVEN, false);
        itemsCircle[16] = new ItemGame(ITEM_APPLE, false);
        itemsCircle[17] = new ItemGame(ITEM_MELLON, true);
        itemsCircle[18] = new ItemGame(ITEM_MELLON, false);
        itemsCircle[19] = new ItemGame(ITEM_STAR, false);
        itemsCircle[20] = new ItemGame(ITEM_STAR, true);
        itemsCircle[21] = new ItemGame(ITEM_MORE_TIME, false);
        itemsCircle[22] = new ItemGame(ITEM_APPLE, false);
        itemsCircle[23] = new ItemGame(ITEM_BELL, true);
    }

    public void update() {
        if (state == STATE_WAITING) {
        } else if (state == STATE_RUNNING) {
            bigLedsSplink();
            smallLedsSplink();
            itemRolling();
        } else if (state == STATE_SHOW_RESULT) {
        }
    }

    public void present(Graphics g) {
        lm.setViewWindow(0, 0, this.getWidth(), this.getHeight());
        g.setColor(0x880000);
        g.fillRect(0, 0, getWidth(), getHeight());
        lm.paint(g, 0, 0);

        for (int i = 0; i < itemsCircle.length; i++) {
            itemsCircle[i].paint(g);
        }
        for (int i = 0; i < listItems.length; i++) {
            listItems[i].paint(g);
            if (screenType == SCREEN_H320) {
                PiPoDesigner.drawCenterString(g, listItems[i].credit + "", 0x00000000, PiPoDesigner.COLOR_RED,
                        textBoxListItems[i].getX() + textBoxListItems[i].getWidth() / 2, textBoxListItems[i].getY());
            } else if (screenType == SCREEN_H240) {
                PiPoDesigner.drawCenterString(g, listItems[i].credit + "", 0x00000000, PiPoDesigner.COLOR_WHITE,
                        listItems[i].getX() + listItems[i].getWidth() / 2, listItems[i].getY() - 16);
            }
        }
        g.setColor(0xffff00);
        if (indexMode == 0) {
            g.drawRoundRect(listItems[indexListItems].getX() - 1, listItems[indexListItems].getY(), listItems[indexListItems].getWidth(),
                    listItems[indexListItems].getHeight(), 5, 5);
        } else if (indexMode == 1) {
            g.drawRoundRect(bigLeds[indexBigLed].getX() - 1, bigLeds[indexBigLed].getY(), bigLeds[indexBigLed].getWidth(),
                    bigLeds[indexBigLed].getHeight(), 5, 5);
        }
        if (screenType == SCREEN_H320) {
            for (int i = 0; i < listItems.length; i++) {
                PiPoDesigner.drawCenterString(g, bonusMultiItem[i] + "", 0x00000000, PiPoDesigner.COLOR_WHITE,
                        listItems[i].getX() + listItems[i].getWidth() / 2, listItems[i].getY() + listItems[i].getHeight() - 4);
            }
        }
        PiPoDesigner.drawCenterString(g, "x " + multiBet, 0x00000000, PiPoDesigner.COLOR_YELOW,
                this.getWidth() / 2, textBoxBigLeds[0].getY() - 10 - 18);
        PiPoDesigner.drawCenterString(g, greenBet + "", 0x00000000, PiPoDesigner.COLOR_RED,
                textBoxBigLeds[0].getX() + textBoxBigLeds[0].getWidth() / 2, textBoxBigLeds[0].getY());
        PiPoDesigner.drawCenterString(g, redBet + "", 0x00000000, PiPoDesigner.COLOR_RED,
                textBoxBigLeds[1].getX() + textBoxBigLeds[1].getWidth() / 2, textBoxBigLeds[1].getY());
        String bonusStr = bonus + "";
//        if (bonus >= 100000) {
//            bonusStr = bonus / 1000 + " K";
//        }
        PiPoDesigner.drawCenterString(g, bonusStr, 0x00000000,
                PiPoDesigner.COLOR_RED, textBoxBonus.getX() + textBoxBonus.getWidth() / 2, textBoxBonus.getY());
        String creditStr = credit + "";
        if (credit >= 100000) {
            creditStr = credit / 1000 + " K";
        }
        PiPoDesigner.drawCenterString(g, creditStr, 0x00000000,
                PiPoDesigner.COLOR_RED, textBoxCredit.getX() + textBoxCredit.getWidth() / 2, textBoxCredit.getY());
        if (screenType == SCREEN_H320) {
            PiPoDesigner.drawString(g, "Tùy chọn", 0x00000000, PiPoDesigner.COLOR_WHITE,
                    0, bottomBar.getY() + (bottomBar.getHeight() - 18) / 2);
            PiPoDesigner.drawString(g, "Bắt đầu", 0x00000000, PiPoDesigner.COLOR_WHITE,
                    this.getWidth() - PiPoDesigner.stringWidth("Bắt đầu"), bottomBar.getY() + (bottomBar.getHeight() - 18) / 2);
        } else if (screenType == SCREEN_H240) {
            PiPoDesigner.drawString(g, "Menu", 0x00000000, PiPoDesigner.COLOR_WHITE,
                    0, this.getHeight() - 20);
            PiPoDesigner.drawString(g, "Bắt đầu", 0x00000000, PiPoDesigner.COLOR_WHITE,
                    this.getWidth() - PiPoDesigner.stringWidth("Bắt đầu"), this.getHeight() - 20);
        }
        if (state == STATE_MENU) {
            drawMenu(g);
        }
        if (isKillClient) {
            paintDialog(g);
        }
        if (isLostConnection) {
            paintDialog(g);
        }
        flushGraphics();
    }

    public void drawMenu(Graphics g) {
        g.setColor(40, 44, 52);
        int yAnchor = 0;
        if (screenType == SCREEN_H320) {
            yAnchor = this.getHeight() - bottomBar.getHeight() - 2 - menuStr.length * 25;
            g.fillRoundRect(2, yAnchor,
                    120, menuStr.length * 25, 7, 7);
            g.setColor(0xffffff);
            g.drawRoundRect(2, yAnchor,
                    120, menuStr.length * 25, 7, 7);
        } else if (screenType == SCREEN_H240) {
            yAnchor = this.getHeight() - 20 - 2 - menuStr.length * 25;
            g.fillRoundRect(2, yAnchor,
                    120, menuStr.length * 25, 7, 7);
            g.setColor(0xffffff);
            g.drawRoundRect(2, yAnchor,
                    120, menuStr.length * 25, 7, 7);
        }
        selectMenu.setPosition(2 + 5, yAnchor + 2 + iMenu * (2 + selectMenu.getHeight()));
        selectMenu.paint(g);
        for (int i = 0; i < menuStr.length; i++) {
            PiPoDesigner.drawString(g, menuStr[i], 0x00000000, PiPoDesigner.COLOR_WHITE,
                    2 + 10, yAnchor + 3 + i * 25);
        }
    }

    private void paintDialog(Graphics g) {
        g.setColor(0x000000);
        g.fillRoundRect(10, this.getHeight() - DIALOG_HEIGHT - 2, this.getWidth() - 20, DIALOG_HEIGHT, 10, 10);
        int stringDialogWidth = PiPoDesigner.stringWidth(dialogString);
        PiPoDesigner.drawString(g, dialogString, PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_WHITE,
                this.getWidth() / 2 - stringDialogWidth / 2, this.getHeight() - DIALOG_HEIGHT);
        g.setColor(0xffffff);
        g.fillRect(15, this.getHeight() - DIALOG_HEIGHT / 2, this.getWidth() - 30, 15);
        PiPoDesigner.drawCenterString(g, "YES", PiPoDesigner.COLOR_BLACK, PiPoDesigner.COLOR_YELOW, this.getWidth() / 2, this.getHeight() - 20);
        g.drawRoundRect(10, this.getHeight() - DIALOG_HEIGHT - 2, this.getWidth() - 20, DIALOG_HEIGHT, 10, 10);
    }

    public void run() {
        int timeGc = 0;
        Graphics g = getGraphics();
        Thread currentThread = Thread.currentThread();
        while (currentThread == gameThread) {
            long startTime = System.currentTimeMillis();
            if (isShown()) {
                try {
                    if (running) {
                        update();
                    }
                    present(g);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                timeGc += delay;
                if (timeGc >= 5000) {
                    Runtime.getRuntime().gc();
                    timeGc = 0;
                }
            }
            long timeTake = System.currentTimeMillis() - startTime;
            if (timeTake < delay) {
                synchronized (this) {
                    try {
                        wait(delay - timeTake);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            } else {
                Thread.currentThread().yield();
            }
        }
        exit();
    }

    public void itemRolling() {
        if (isWaitMoreTime) {
            timeWaitMoreTime += delay;
            if (timeWaitMoreTime <= 500) {
                itemsCircle[indexItemRolling + 1].bg.nextFrame();
            } else {
                isWaitMoreTime = false;
            }
            return;
        }
        timeItemChange += delay;
        if (timeChangeSpeed <= 2000) {
            if (timeItemChange >= 200) {
                timeItemChange = 0;
                for (int i = 0; i < itemsCircle.length; i++) {
                    itemsCircle[i].bgSetFrame(0);
                }
                itemsCircle[indexItemRolling].bgSetFrame(1);
                if (isTurnRight) {
                    if (indexItemRolling < itemsCircle.length - 1) {
                        indexItemRolling++;
                    } else {
                        indexItemRolling = 0;
                    }
                } else if (isTurnLeft) {
                    if (indexItemRolling > 0) {
                        indexItemRolling--;
                    } else {
                        indexItemRolling = itemsCircle.length - 1;
                    }
                }
            }
        } else if (timeChangeSpeed <= 4000) {
            if (timeItemChange >= 50) {
                timeItemChange = 0;
                for (int i = 0; i < itemsCircle.length; i++) {
                    itemsCircle[i].bgSetFrame(0);
                }
                itemsCircle[indexItemRolling].bgSetFrame(1);
                if (isTurnRight) {
                    if (indexItemRolling < itemsCircle.length - 1) {
                        indexItemRolling++;
                    } else {
                        indexItemRolling = 0;
                    }
                } else if (isTurnLeft) {
                    if (indexItemRolling > 0) {
                        indexItemRolling--;
                    } else {
                        indexItemRolling = itemsCircle.length - 1;
                    }
                }
            }
        } else {
            if (timeChangeSpeed >= 5000) {
                Random r = new Random();
                int ran = typeLed;
                if (ran == 0) {
                    bigLeds[0].setFrame(1);
                    bigLeds[1].setFrame(0);
                } else {
                    bigLeds[0].setFrame(0);
                    bigLeds[1].setFrame(1);
                }
                countBigSplink = 100;
            }
            if (timeItemChange >= 200) {
                if (timeChangeSpeed >= 5000) {
                    int t1, t2;
                    if (itemsCircle[indexItemRolling].isSmall) {
                        t1 = 1;
                    } else {
                        t1 = 2;
                    }
                    if (isItemFinalSmall) {
                        t2 = 1;
                    } else {
                        t2 = 2;
                    }
                    if (itemsCircle[indexItemRolling].type == ITEM_MORE_TIME) {
                        t1 = 1;
                    }
                    if (typeItemFinal == ITEM_MORE_TIME) {
                        t2 = 1;
                    }
                    if ((itemsCircle[indexItemRolling].type == typeItemFinal) && (t1 == t2)) {
                        state = STATE_SHOW_RESULT;
                        if (typeItemFinal == ITEM_MORE_TIME) {
                            state = STATE_RUNNING;
                            resetAllTime();
                            typeItemFinal = buffertypeItemFinal;
                            typeLed = bufferTypeLed;
                            isItemFinalSmall = bufferIsItemFinalSmall;
//                            String dataCredit = "";
//                            for (int i = 0; i < listItems.length; i++) {
//                                dataCredit += listItems[i].credit + "|";
//                            }
//                            dataCredit += greenBet + "|";
//                            dataCredit += redBet + "|";
//                            Request.sendLuckCoinCredit(dataCredit);
//                            randomItemResult();
                            isWaitMoreTime = true;
                            if (isItemFinalSmall) {
                                isTurnLeft = true;
                                isTurnRight = false;
                            } else {
                                isTurnRight = true;
                                isTurnLeft = false;
                            }
                        } else {
                            calResult();
                        }
                    }
                }
                timeItemChange = 0;
                for (int i = 0; i < itemsCircle.length; i++) {
                    itemsCircle[i].bgSetFrame(0);
                }
                itemsCircle[indexItemRolling].bgSetFrame(1);
                if (isTurnRight) {
                    if (indexItemRolling < itemsCircle.length - 1) {
                        indexItemRolling++;
                    } else {
                        indexItemRolling = 0;
                    }
                } else if (isTurnLeft) {
                    if (indexItemRolling > 0) {
                        indexItemRolling--;
                    } else {
                        indexItemRolling = itemsCircle.length - 1;
                    }
                }
            }
        }
    }

    public void bigLedsSplink() {
        countBigSplink += delay;
        if (countBigSplink >= 200) {
            for (int i = 0; i < bigLeds.length; i++) {
                bigLeds[i].nextFrame();
            }
            countBigSplink = 0;
        }
    }

    public void smallLedsSplink() {
        timeChangeSpeed += delay;
        timeSmLedSplink += delay;
        if (timeChangeSpeed <= 2000) {
            if (timeSmLedSplink >= 200) {
                timeSmLedSplink = 0;
                for (int i = 0; i < smallLeds.length; i++) {
                    smallLeds[i].setFrame(0);
                }
                smallLeds[indexSmallLed].setFrame(1);
                if (indexSmallLed < smallLeds.length - 1) {
                    indexSmallLed++;
                } else {
                    indexSmallLed = 0;
                }
            }
        } else if (timeChangeSpeed <= 4000) {
            if (timeSmLedSplink >= 100) {
                timeSmLedSplink = 0;
                for (int i = 0; i < smallLeds.length; i++) {
                    smallLeds[i].setFrame(0);
                }
                smallLeds[indexSmallLed].setFrame(1);
                if (indexSmallLed < smallLeds.length - 1) {
                    indexSmallLed++;
                } else {
                    indexSmallLed = 0;
                }
            }
        } else {
            if (timeSmLedSplink >= 200) {
                timeSmLedSplink = 0;
                for (int i = 0; i < smallLeds.length; i++) {
                    smallLeds[i].setFrame(0);
                }
                smallLeds[indexSmallLed].setFrame(1);
                if (indexSmallLed < smallLeds.length - 1) {
                    indexSmallLed++;
                } else {
                    indexSmallLed = 0;
                }
            }
        }
    }

    public void randomItemResult() {
        Random r = new Random();
        int t = r.nextInt(100);
        if (t <= 5) {
            typeItemFinal = ITEM_APPLE;
            isItemFinalSmall = true;
        } else if (t <= 10) {
            typeItemFinal = ITEM_ORANGE;
            isItemFinalSmall = true;
        } else if (t == 11) {
            int t1 = r.nextInt(4);
//            if (t1 == 1 || t1 == 2) {
//                t1 = 0;
//            }
            if (t1 == 0) {
                typeItemFinal = ITEM_BAR;
                isItemFinalSmall = true;
            } else if (t1 == 1) {
                typeItemFinal = ITEM_MORE_TIME;
                isItemFinalSmall = true; // trái
            } else if (t1 == 2) {
                typeItemFinal = ITEM_MORE_TIME;
                isItemFinalSmall = false; // phải
            } else if (t1 == 3) {
                typeItemFinal = ITEM_BAR;
                isItemFinalSmall = false; // Bar to, ra đổi tiền thôi >.<
            }
        } else if (t <= 31) {
            typeItemFinal = ITEM_APPLE;
            isItemFinalSmall = false;
        } else if (t <= 51) {
            typeItemFinal = ITEM_ORANGE;
            isItemFinalSmall = false;
        } else if (t <= 61) {
            typeItemFinal = ITEM_MELLON;
            isItemFinalSmall = true;
        } else if (t <= 71) {
            typeItemFinal = ITEM_BELL;
            isItemFinalSmall = true;
        } else if (t <= 81) {
            typeItemFinal = ITEM_WATER_MELLON;
            isItemFinalSmall = true;
        } else if (t <= 85) {
            typeItemFinal = ITEM_STAR;
            isItemFinalSmall = true;
        } else if (t <= 89) {
            typeItemFinal = ITEM_SEVEN;
            isItemFinalSmall = true;
        } else if (t <= 91) {
            typeItemFinal = ITEM_SEVEN;
            isItemFinalSmall = false;
        } else if (t <= 93) {
            typeItemFinal = ITEM_STAR;
            isItemFinalSmall = false;
        } else if (t <= 95) {
            typeItemFinal = ITEM_WATER_MELLON;
            isItemFinalSmall = false;
        } else if (t <= 97) {
            typeItemFinal = ITEM_BELL;
            isItemFinalSmall = false;
        } else if (t <= 99) {
            typeItemFinal = ITEM_MELLON;
            isItemFinalSmall = false;
        }
        System.out.println(t + "," + typeItemFinal + ", " + isItemFinalSmall);
    }

    public void calResult() {
        bonus = tempBonus;
//        if (bigLeds[0].getFrame() == 1) {
//            bonus += greenBet * 2 * multiBet;
//        } else {
//            bonus += redBet * 2 * multiBet;
//        }
//        if (isItemFinalSmall) {
//            if (typeItemFinal != ITEM_BAR) {
//                bonus += listItems[typeItemFinal - 1].credit * 2 * multiBet;
//            } else {
//                bonus += listItems[typeItemFinal - 1].credit * 50 * multiBet;
//            }
//        } else {
//            bonus += listItems[typeItemFinal - 1].credit * bonusMultiItem[typeItemFinal - 1] * multiBet;
//        }
    }

    public void resetForNewTurn() {
        credit += bonus;
        checkpointCredit = credit;
        bonus = 0;
        for (int i = 0; i < listItems.length; i++) {
            listItems[i].credit = 0;
        }
        greenBet = redBet = 0;
        state = STATE_WAITING;
        resetAllTime();
    }

    public void resetAllTime() {
        timeWaitMoreTime = 0;
        timeChangeSpeed = 0;
        timeItemChange = 0;
        timeSmLedSplink = 0;
        countBigSplink = 0;
    }

    public int getAllBet() {
        int total = 0;
        for (int i = 0; i < listItems.length; i++) {
            total += listItems[i].credit * multiBet;
        }
        return total + greenBet * multiBet + redBet * multiBet;
    }

    private void checkScreenType() {
        if (this.getHeight() < 300) {
            screenType = SCREEN_H240;
        } else {
            screenType = SCREEN_H320;
        }
    }

    protected void keyPressed(int keyCode) {
        int instantkeyCode = KeyCodeAdapter.getInstance().adoptKeyCode(keyCode);
        switch (instantkeyCode) {
            case KeyCodeAdapter.LEFT_KEY:
                leftKeyPressed();
                return;
            case KeyCodeAdapter.RIGHT_KEY:
                rightKeyPressed();
                return;
            case KeyCodeAdapter.UP_KEY:
                upKeyPressed();
                return;
            case KeyCodeAdapter.DOWN_KEY:
                downKeyPressed();
                return;
            case KeyCodeAdapter.CENTER_KEY:
                fireKeyPressed();
                return;
            case KeyCodeAdapter.SOFT_KEY_LEFT:
                softKeyLeftPressed();
                return;
            case KeyCodeAdapter.SOFT_KEY_RIGHT:
                softKeyRightPressed();
                return;
            case KeyCodeAdapter.KEY__POUND:
                keyPoundPressed();
                return;
            case KeyCodeAdapter.KEY__STAR:
                keyStarPressed();
                return;
            case KeyCodeAdapter.KEY_2:
                upKeyPressed();
                return;
            case KeyCodeAdapter.KEY_8:
                downKeyPressed();
                return;
            case KeyCodeAdapter.KEY_4:
                leftKeyPressed();
                return;
            case KeyCodeAdapter.KEY_6:
                rightKeyPressed();
                return;
            case KeyCodeAdapter.KEY_5:
                fireKeyPressed();
                return;
        }
    }

    public void upKeyPressed() {
        if (state == STATE_SHOW_RESULT) {
            resetForNewTurn();
        }
        if (state == STATE_WAITING) {
            if (credit >= multiBet) {
                if (listItems[indexListItems].credit < 99) {
                    listItems[indexListItems].credit++;
                    credit -= multiBet;
                }
            }
//            if (indexMode < 1) {
//                indexMode++;
//            } else {
//                indexMode = 1;
//            }
        } else if (state == STATE_MENU) {
            if (iMenu > 0) {
                iMenu--;
            } else {
                iMenu = menuStr.length - 1;
            }
        }
    }

    public void downKeyPressed() {
        if (state == STATE_SHOW_RESULT) {
            resetForNewTurn();
        }
        if (state == STATE_WAITING) {
            if (listItems[indexListItems].credit > 0) {
                listItems[indexListItems].credit--;
                credit += multiBet;
            }
//            if (indexMode > 0) {
//                indexMode--;
//            } else {
//                indexMode = 1;
//            }
        } else if (state == STATE_MENU) {
            if (iMenu < menuStr.length - 1) {
                iMenu++;
            } else {
                iMenu = 0;
            }
        }
    }

    public void rightKeyPressed() {
        if (state == STATE_SHOW_RESULT) {
            resetForNewTurn();
        }
        if (state == STATE_WAITING) {
            if (indexMode == 0) {
                if (indexListItems > 0) {
                    indexListItems--;
                } else {
                    indexListItems = listItems.length - 1;
                }
            } else {
                if (indexBigLed > 0) {
                    indexBigLed--;
                } else {
                    indexBigLed = 1;
                }
            }
        }
    }

    public void leftKeyPressed() {
        if (state == STATE_SHOW_RESULT) {
            resetForNewTurn();
        }
        if (state == STATE_WAITING) {
            if (indexMode == 0) {
                if (indexListItems < listItems.length - 1) {
                    indexListItems++;
                } else {
                    indexListItems = 0;
                }
            } else {
                if (indexBigLed < 1) {
                    indexBigLed++;
                } else {
                    indexBigLed = 0;
                }
            }
        }
    }

    public void fireKeyPressed() {
        if (isKillClient) {
            midlet.disposeLuckyCoin();
            midlet.displayMainCanvas(0);
            return;
        }
        if (isLostConnection) {
            midlet.disposeLuckyCoin();
            midlet.displayMainCanvas(0);
            return;
        }
        if (state == STATE_SHOW_RESULT) {
            resetForNewTurn();
        }
        if (state == STATE_WAITING) {
            if (credit <= 0) {
                credit = 0;
                return;
            }
            if (indexMode == 0) {
                if (credit >= multiBet) {
                    if (listItems[indexListItems].credit < 99) {
                        listItems[indexListItems].credit++;
                        credit -= multiBet;
                    } else {
                        listItems[indexListItems].credit = 0;
                        credit += 99 * multiBet;
                    }
                }
            } else if (indexMode == 1) {
                if (indexBigLed == 0) {
                    if (greenBet < 90) {
                        greenBet += 10;
                        credit -= 10 * multiBet;
                    } else {
                        greenBet = 0;
                        credit += 90 * multiBet;
                    }
                } else if (indexBigLed == 1) {
                    if (redBet < 90) {
                        redBet += 10;
                        credit -= 10 * multiBet;
                    } else {
                        redBet = 0;
                        credit += 90 * multiBet;
                    }
                }
            }
        }
        if (state == STATE_MENU) {
            state = STATE_WAITING;
            if (iMenu == 0) {
                int total = 0;
                for (int i = 0; i < listItems.length; i++) {
                    total += listItems[i].credit * 10000;
                }
                total += greenBet * 10000 + redBet * 10000;
                if (checkpointCredit >= total) {
                    multiBet = 10000;
                    credit = checkpointCredit - getAllBet();
                }
            } else if (iMenu == 1) {
                int total = 0;
                for (int i = 0; i < listItems.length; i++) {
                    total += listItems[i].credit * 1000;
                }
                total += greenBet * 1000 + redBet * 1000;
                if (checkpointCredit >= total) {
                    multiBet = 1000;
                    credit = checkpointCredit - getAllBet();
                }
            } else if (iMenu == 2) {
                int total = 0;
                for (int i = 0; i < listItems.length; i++) {
                    total += listItems[i].credit * 100;
                }
                total += greenBet * 100 + redBet * 100;
                if (checkpointCredit >= total) {
                    multiBet = 100;
                    credit = checkpointCredit - getAllBet();
                }
            } else if (iMenu == 3) {
                credit = checkpointCredit;
                bonus = 0;
                for (int i = 0; i < listItems.length; i++) {
                    listItems[i].credit = 0;
                }
                greenBet = redBet = 0;
                state = STATE_WAITING;
                multiBet = 1;
                resetAllTime();
            } else if (iMenu == 4) {
                Debug.d("exit");
                running = false;
                gameThread = null;

            }
        }
    }

    private void exit() {
        midlet.displayMainCanvas(1);
        midlet.disposeLuckyCoin();
    }

    public void softKeyLeftPressed() {
        if (isKillClient) {
            midlet.disposeLuckyCoin();
            midlet.displayMainCanvas(0);
            return;
        }
        if (isLostConnection) {
            midlet.disposeLuckyCoin();
            midlet.displayMainCanvas(0);
            return;
        }
        if (state == STATE_WAITING || state == STATE_SHOW_RESULT) {
            checkPointState = state;
            if (state == STATE_SHOW_RESULT) {
                resetForNewTurn();
            }
            state = STATE_MENU;
        } else if (state == STATE_MENU) {
            state = checkPointState;
        }
    }

    public void softKeyRightPressed() {
        if (isKillClient) {
            midlet.disposeLuckyCoin();
            midlet.displayMainCanvas(0);
            return;
        }
        if (isLostConnection) {
            midlet.disposeLuckyCoin();
            midlet.displayMainCanvas(0);
            return;
        }
        if (state == STATE_WAITING) {
            if (getAllBet() > 0 && credit >= 0 && checkpointCredit >= 0) {
                checkpointCredit = credit;
                String dataCredit = "";
                for (int i = 0; i < listItems.length; i++) {
                    dataCredit += listItems[i].credit * multiBet + "|";
                }
                dataCredit += greenBet * multiBet + "|";
                dataCredit += redBet * multiBet + "|";
                Request.sendLuckCoinCredit(dataCredit);
                state = STATE_RUNNING;
//                randomItemResult();
            }
        } else if (state == STATE_SHOW_RESULT) {
            credit += bonus;
            bonus = 0;
            if (credit >= 0 && credit >= getAllBet()) {
                String dataCredit = "";
                for (int i = 0; i < listItems.length; i++) {
                    dataCredit += listItems[i].credit * multiBet + "|";
                }
                dataCredit += greenBet * multiBet + "|";
                dataCredit += redBet * multiBet + "|";
                Request.sendLuckCoinCredit(dataCredit);
                state = STATE_RUNNING;
                credit -= getAllBet();
                checkpointCredit = credit;
                resetAllTime();
//                randomItemResult();
            }
        } else if (state == STATE_MENU) {
            state = checkPointState;
        }
    }

    public void keyPoundPressed() {
        if (state == STATE_SHOW_RESULT) {
            resetForNewTurn();
        }
        if (state == STATE_WAITING) {
            if (credit >= 10 * multiBet) {
                if (greenBet < 90) {
                    greenBet += 10;
                    credit -= 10 * multiBet;
                } else {
                    greenBet = 0;
                    credit += 90 * multiBet;
                }
            }
        }
    }

    public void keyStarPressed() {
        if (state == STATE_SHOW_RESULT) {
            resetForNewTurn();
        }
        if (state == STATE_WAITING) {
            if (credit >= 10 * multiBet) {
                if (redBet < 90) {
                    redBet += 10;
                    credit -= 10 * multiBet;
                } else {
                    redBet = 0;
                    credit += 90 * multiBet;
                }
            }
        }
    }

    protected void pointerPressed(int x, int y) {
        super.pointerPressed(x, y);
    }

    protected void pointerReleased(int x, int y) {
        super.pointerReleased(x, y);
        int xAnchorOk = 0;
        int yAnchorOk = this.getHeight() - 40;
        int xAnchorCancel = this.getWidth() - 15 - PiPoDesigner.stringWidth("Bỏ qua");
        int yAnchorCancel = this.getHeight() - 40;
        if (inBounds(x, y, xAnchorOk, yAnchorOk, 50, 50)) {
            softKeyLeftPressed();
        } else if (inBounds(x, y, xAnchorCancel, yAnchorCancel, 50, 50)) {
            softKeyRightPressed();
        }
        return;
    }

    protected void pointerDragged(int x, int y) {
        super.pointerDragged(x, y);
    }

    private boolean inBounds(int pointerX, int pointerY, int boxX, int boxY, int width,
            int height) {
        if (pointerX > boxX && pointerX < boxX + width - 1 && pointerY > boxY
                && pointerY < boxY + height - 1) {
            return true;
        } else {
            return false;
        }
    }

    public void processMessage(String[] part) {
        if (part[0].equals("KILL")) {
            dialogString = "Có người đã đăng nhập nick của bạn";
            isKillClient = true;
            return;
        }
        if (part[0].equals("QUIT") && !isKillClient) {
            dialogString = "Mất kết nối mạng";
            isLostConnection = true;
            return;
        }
        if (part[0].equals("PING")) {
            Request.ping();
            return;
        }
        if (part[0].equalsIgnoreCase("INFO")) {
//              GameData.getInstance().setMyMoney(bonus);
            credit = Long.parseLong(part[1]);
            checkpointCredit = credit;
        } else if (part[0].equalsIgnoreCase("RA")) {
            if (typeItemFinal == ITEM_MORE_TIME) {
                bufferTypeLed = Integer.parseInt(part[1]);
                buffertypeItemFinal = Integer.parseInt(part[2]);
                if (buffertypeItemFinal == 0) {
                    buffertypeItemFinal = ITEM_APPLE;
                } else if (buffertypeItemFinal == 1) {
                    buffertypeItemFinal = ITEM_ORANGE;
                } else if (buffertypeItemFinal == 2) {
                    buffertypeItemFinal = ITEM_MELLON;
                } else if (buffertypeItemFinal == 3) {
                    buffertypeItemFinal = ITEM_BELL;
                } else if (buffertypeItemFinal == 4) {
                    buffertypeItemFinal = ITEM_WATER_MELLON;
                } else if (buffertypeItemFinal == 5) {
                    buffertypeItemFinal = ITEM_STAR;
                } else if (buffertypeItemFinal == 6) {
                    buffertypeItemFinal = ITEM_SEVEN;
                } else if (buffertypeItemFinal == 7) {
                    buffertypeItemFinal = ITEM_BAR;
                } else if (buffertypeItemFinal == 8) {
                    buffertypeItemFinal = ITEM_MORE_TIME;
                }
                int kindItemFinal = Integer.parseInt(part[3]);
                if (kindItemFinal == 0) {
                    bufferIsItemFinalSmall = true;
                } else {
                    bufferIsItemFinalSmall = false;
                }
            } else {
                typeLed = Integer.parseInt(part[1]);
                typeItemFinal = Integer.parseInt(part[2]);
                if (typeItemFinal == 0) {
                    typeItemFinal = ITEM_APPLE;
                } else if (typeItemFinal == 1) {
                    typeItemFinal = ITEM_ORANGE;
                } else if (typeItemFinal == 2) {
                    typeItemFinal = ITEM_MELLON;
                } else if (typeItemFinal == 3) {
                    typeItemFinal = ITEM_BELL;
                } else if (typeItemFinal == 4) {
                    typeItemFinal = ITEM_WATER_MELLON;
                } else if (typeItemFinal == 5) {
                    typeItemFinal = ITEM_STAR;
                } else if (typeItemFinal == 6) {
                    typeItemFinal = ITEM_SEVEN;
                } else if (typeItemFinal == 7) {
                    typeItemFinal = ITEM_BAR;
                } else if (typeItemFinal == 8) {
                    typeItemFinal = ITEM_MORE_TIME;
                }
                int kindItemFinal = Integer.parseInt(part[3]);
                if (kindItemFinal == 0) {
                    isItemFinalSmall = true;
                } else {
                    isItemFinalSmall = false;
                }
            }
        } else if (part[0].equalsIgnoreCase("CM")) {
            tempBonus = Integer.parseInt(part[1]);
        }
    }

    public void setDialogString(String message) {
    }

    public class ItemGame {

        public Sprite item;
        public Sprite bg;
        public boolean isSmall;
        public int credit;
        public int type;

        public ItemGame(int type, boolean isSmall) {
            bg = design.getBackItem();
            item = design.getItem(type, isSmall);
            this.type = type;
            this.isSmall = isSmall;
        }

        public void setPosition(int x, int y) {
            bg.setPosition(x, y);
            item.setPosition(x, y);
        }

        public void bgNextFrame() {
            bg.nextFrame();
        }

        public void bgSetFrame(int frame) {
            bg.setFrame(frame);
        }

        public int bgGetFrame() {
            return bg.getFrame();
        }

        public int getWidth() {
            return bg.getWidth();
        }

        public int getHeight() {
            return bg.getHeight();
        }

        public int getX() {
            return bg.getX();
        }

        public int getY() {
            return bg.getY();
        }

        public void paint(Graphics g) {
            bg.paint(g);
            item.paint(g);
        }
    }
}
